import { _decorator, Component, EditBox, director } from 'cc'
import { ApiMsgEnum } from '../Common'
import { SceneEnum } from '../Enum'
import DataManager from '../Global/DataManager'
import { NetworkManager } from '../Global/NetworkManager'

const { ccclass } = _decorator

// 登录场景
@ccclass('LoginManager')
export class LoginManager extends Component {
  input: EditBox // 输入框
  onLoad() {
    // 获取输入组件
    this.input = this.getComponentInChildren(EditBox)
    // 预加载场景
    director.preloadScene(SceneEnum.Hall)
  }

  // 网络初始化
  async start() {
    await NetworkManager.Instance.connect()
  }

  // 点击登录
  async handleClick() {
    if (!NetworkManager.Instance.isConnected) {
      console.log('网络未连接')
      await NetworkManager.Instance.connect()
      return
    }

    const nickname = this.input.string
    if (!nickname) {
      return console.log('请先输入昵称！')
    }

    const { success, error, res } = await NetworkManager.Instance.callApi(ApiMsgEnum.ApiPlayerJoin, { nickname })
    if (!success) return console.log('api错误：', error)

    DataManager.Instance.playerID = res.player.id
    // 场景切换
    director.loadScene(SceneEnum.Hall)
  }
}
